package com.justRun;

import android.os.SystemClock;
import android.widget.Chronometer;

public class Chronometre {
	private boolean running = false;
	private Chronometer chrono;
	private long temps = 0;

	public Chronometre(Chronometer c) {
		chrono = c;
		chrono.setText("00:00:00");
		chrono.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
			@Override
			public void onChronometerTick(Chronometer chronometer) {
				CharSequence text = chronometer.getText();
				if (text.length() == 5) {
					chronometer.setText("00:"+text);
				} else if (text.length() == 7) {
					chronometer.setText("0"+text);
				}
			}
		});
	}

	public long getTempsPasse() {
		if (running) temps = SystemClock.elapsedRealtime() - chrono.getBase();
		return temps;
	}

	public void start() {
		if (!running) {
			chrono.setBase(SystemClock.elapsedRealtime());				
			chrono.start();
			running = true;
		}
	}

	public void reset() {
		chrono.setBase(SystemClock.elapsedRealtime());
		chrono.setText("00:00:00");
	}

	public void stop() {
		chrono.stop();
		temps = SystemClock.elapsedRealtime() - chrono.getBase();
		running = false;
	}

	public void reprendre() {
		chrono.setBase(SystemClock.elapsedRealtime() - temps);
		chrono.start();
		running = true;
	}

	public void setTempsPasse(double tpsPasse) {
		temps = (long) tpsPasse;
		chrono.setBase(SystemClock.elapsedRealtime() - temps);
		CharSequence text = chrono.getText();
		if (text.length() == 5) {
			chrono.setText("00:"+text);
		} else if (text.length() == 7) {
			chrono.setText("0"+text);
		}
	}
}
